package cn.dgut.jy.soro.config;



import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@EnableTransactionManagement
@Configuration
public class JpaConfig {
    private final Environment env;

    public JpaConfig(Environment env) {
        this.env = env;
    }

    // 配置MySql数据源
    @Bean
    @Primary// 设置主数据库
    public DataSource jdbcDataSource() {

        MysqlDataSource source = new MysqlDataSource();
        // 从属性文件读取属性值
        source.setUrl(env.getProperty("spring.datasource.url"));
        System.out.println(env.getProperty("spring.datasource.url"));
        source.setUser(env.getProperty("spring.datasource.username"));
        source.setPassword(env.getProperty("spring.datasource.password"));// 读取属性文件中的password属性
        return source;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        // 显示sql语句
        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL8Dialect");// Mysql 8.X

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        factory.setPackagesToScan("cn.dgut.jy.soro");

        factory.setDataSource(dataSource);
        return factory;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}
